package org.jin.samples.dao.impl;

import java.util.List;

import org.hibernate.type.StringType;
import org.jin.samples.dao.ISubjectDao;
import org.jin.samples.model.ExamScore;
import org.jin.samples.model.ExamSubject;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;


@Repository
@Transactional
public class SubjectDaoImpl extends BaseHibernateDAO<ExamSubject> implements ISubjectDao{

	@SuppressWarnings("unchecked")	
	public List<String> getAllUserBySubjectId(Integer subjectId){
		StringBuffer sql = new StringBuffer();
		sql.append(" select user.user_id as userId ");
		sql.append(" from exam_user_subject eus ");
		sql.append(" left join exam_subject es on eus.sub_id = es.sub_id ");
		sql.append(" left join exam_user user on user.user_id = eus.user_id ");
		sql.append(" where es.sub_id =:subjectId ");
		
		return this.createSqlQuery(String.valueOf(sql))
					.addScalar("userId", StringType.INSTANCE)
					.setInteger("subjectId", subjectId)
					.list();			
	}
	
	@Override
	public void insertSubjectUsers(List<String> insertList, Integer subjectId){
		String sql = null;
		//添加多条数据
		for(String userId : insertList){
			sql = "insert into exam_user_subject(user_id, sub_id) values(:userId, :subjectId)";
			this.createSqlQuery(sql).setString("userId", userId).setInteger("subjectId", subjectId).executeUpdate();
		}
	}
	
	@Override
	public void deleteSubjectUsers(List<String> delList, Integer subjectId){
		String sql = null;
		//伤处多条数据
		for(String userId : delList){
			sql = "delete exam_user_subject from exam_user_subject where user_id =:userId and sub_id =:subjectId ";
			this.createSqlQuery(sql).setString("userId", userId).setInteger("subjectId", subjectId).executeUpdate();
		}
	}

	@Override
	public ExamSubject findAllBySubjectId(Integer subjectId){
		//String hql = "FROM ExamSubject WHERE sub_id = ?";
		//List<ExamSubject> list = this.queryForList(hql, new Object[]{subjectId});
		
		return this.get(subjectId);
		
	}
}
